<?php
/**
* @file $Id: TakeAttendance.php 451 2007-04-23 04:30:11Z focus-sis $
* @package Focus/SIS
* @copyright Copyright (C) 2006 Andrew Schmadeke. All rights reserved.
* @license http://www.gnu.org/copyleft/gpl.html GNU/GPL, see LICENSE.txt
* Focus/SIS is free software. This version may have been modified pursuant
* to the GNU General Public License, and as distributed it includes or
* is derivative of works licensed under the GNU General Public License or
* other free or open source software licenses.
* See COPYRIGHT.txt for copyright notices and details.
*/

DrawHeader(ProgramTitle());
$_FOCUS['allow_edit'] = true;

if (!isset($_REQUEST['table'])) {
	$_REQUEST['table'] = 0;
}

if ($_REQUEST['table'] == 0) {
	$table = 'ATTENDANCE_PERIOD';
}
else {
	$table = 'LUNCH_PERIOD';
}

$db_date = DbDate();
$user_period = UserPeriod();
$user_course_period = UserCoursePeriod();
$user_staff_id = User('STAFF_ID');
$user_school = UserSchool();
$user_syear = UserSyear();
$current_marking_period = GetCurrentMP('QTR', $db_date);
$mp_list = GetAllMP('QTR',GetCurrentMP('QTR',$db_date));

$can_take_attendnace = DBGet(DBQuery("
		SELECT       DOES_ATTENDANCE
		 ,           CALENDAR_ID 
		FROM         COURSE_PERIODS 
		WHERE        COURSE_PERIOD_ID = '$user_course_period'
		"));
$calendar_id = $can_take_attendnace[1]['CALENDAR_ID'];
$can_take_attendnace = $can_take_attendnace[1]['DOES_ATTENDANCE'];
		
if ($_REQUEST['table'] == '0') {
	if ($can_take_attendnace != 'Y') {
		DrawHeader(ErrorMessage(array(_('You cannot take attendance on this period.'))
				, 'fatal'), ' &nbsp;');
	}
	
	$days = DBGet(DBQuery("
			SELECT       DAYS 
			FROM         COURSE_PERIODS 
			WHERE        COURSE_PERIOD_ID = '$user_course_period'
			"));

	$day = DayNameToLetter(date('D'));
	
	if (substr($days[1]['DAYS'], $day) === false) {
		DrawHeader(ErrorMessage(array(_('You cannot take attendance today since this class doesn\'t meet today.')), 'fatal'), ' &nbsp;');
	}
}

// this purposefully grabs all attendance for this period beacause if we dont, we could create a duplicate primary key
$current_RET = DBGet(DBQuery("
		SELECT       ATTENDANCE_TEACHER_CODE
		 ,           STUDENT_ID
		 ,           ADMIN 
		FROM         $table 
		WHERE        SCHOOL_DATE = '$db_date'
		 AND         PERIOD_ID = '$user_period'
		 AND         MARKING_PERIOD_ID in($mp_list) "
		.(($table == 'LUNCH_PERIOD') ? " 
		 AND TABLE_NAME = '$_REQUEST[table]'"
		 : '')), array(), array('STUDENT_ID'));

if ($_REQUEST['attendance'] 
&&  $_POST['attendance']
){
	foreach ($_REQUEST['attendance'] as $student_id=>$value) {
		$attendance_code = substr($value,  5);

		if ($current_RET[$student_id]) {
			$sql = "
					UPDATE       $table
					SET          ATTENDANCE_TEACHER_CODE = '$attendance_code'
					 ,           COURSE_PERIOD_ID = '$user_course_period' ";
					
			if ($current_RET[$student_id][1]['ADMIN']!='Y') {
				$sql .= "
					 ,           ATTENDANCE_CODE = '$attendance_code' ";
			}
			
			$sql .= "
					WHERE        SCHOOL_DATE = '$db_date' 
					 AND         PERIOD_ID = '$user_period' 
					 AND         STUDENT_ID = '$student_id'
					";
		}
		else {
			$sql = "
					INSERT INTO  $table 
					(  STUDENT_ID
					 , SCHOOL_DATE
					 , MARKING_PERIOD_ID
					 , PERIOD_ID
					 , COURSE_PERIOD_ID
					 , ATTENDANCE_CODE
					 , ATTENDANCE_TEACHER_CODE "
					 . (($table == 'LUNCH_PERIOD') ? ', TABLE_NAME' : '') ."
					) VALUES
					(  '$student_id'
					 , '$db_date'
					 , '$current_marking_period'
					 , '$user_period'
					 , '$user_course_period'
					 , '$attendance_code'
					 , '$attendance_code'"
					 . (($table == 'LUNCH_PERIOD') ? "
					 , '$_REQUEST[table]'" : '') ."
					)
					";
		}

		DBQuery($sql);
		
		if ($_REQUEST['table'] == '0') {		
			UpdateAttendanceDaily($student_id, $db_date);
		}
	}
	
	if ($_REQUEST['table'] == '0')
	{
		$RET = DBGet(DBQuery("
				SELECT       'completed' AS COMPLETED 
				FROM         ATTENDANCE_COMPLETED 
				WHERE        STAFF_ID = '$user_staff_id' 
				 AND         SCHOOL_DATE = '$db_date' 
				 AND         PERIOD_ID='$user_period'
				"));
				
		if (!count($RET)) {
			DBQuery("
					INSERT INTO  ATTENDANCE_COMPLETED 
					(  STAFF_ID
					 , SCHOOL_DATE
					 , PERIOD_ID
					) VALUES
					(  '$user_staff_id'
					 , '$db_date'
					 , '$user_period'
					)
					");
		}
	}

	// now, query just the records that are assigned to this course period
	$current_RET = DBGet(DBQuery("
			SELECT       ATTENDANCE_TEACHER_CODE
			 ,           STUDENT_ID
			 ,           ADMIN 
			FROM         $table 
			WHERE        SCHOOL_DATE = '$db_date'
			 AND         COURSE_PERIOD_ID = '$user_course_period' "
			.(($table == 'LUNCH_PERIOD') ? " 
			 AND TABLE_NAME = '$_REQUEST[table]'"
			: '')), array(), array('STUDENT_ID'));
			
	unset($_SESSION['_REQUEST_vars']['attendance']);
	unset($_REQUEST['attendance']);
}

if (SystemPreferences('PAST_ATTENDANCE_DAYS') != 0) {
	if ($DatabaseType != 'oracle') {
		$limit = ' LIMIT ' . SystemPreferences('PAST_ATTENDANCE_DAYS');
	}
	
	if ($calendar_id) {
		$dates_RET = DBGet(DBQuery("
				SELECT       to_char(SCHOOL_DATE, 'YYYY-MM-DD') as SCHOOL_DATE 
				FROM         ATTENDANCE_CALENDAR 
				WHERE        CALENDAR_ID = '$calendar_id' 
				 AND         SCHOOL_DATE < '$db_date' 
				ORDER BY     SCHOOL_DATE DESC 
				" . $limit));
	}
	else {
		$dates_RET = DBGet(DBQuery("
				SELECT       to_char(SCHOOL_DATE, 'YYYY-MM-DD') AS SCHOOL_DATE 
				FROM         ATTENDANCE_CALENDAR 
				WHERE        SCHOOL_DATE < '$db_date' 
				ORDER BY     SCHOOL_DATE DESC 
				" . $limit));
	}
	
	for($i = SystemPreferences('PAST_ATTENDANCE_DAYS'); $i >= 1; $i--) {
		$school_dates .= ", '" . $dates_RET[$i]['SCHOOL_DATE'] . "'";
	}

	$school_dates = substr($school_dates, 1);
}

if (SystemPreferences('PAST_ATTENDANCE_DAYS') != 0 
&&  $_REQUEST['past_attendance'] 
&&  $_POST['attendance']
){			
	$current_past_RET = DBGet(DBQuery("
			SELECT       ATTENDANCE_TEACHER_CODE
			 ,           STUDENT_ID
			 ,           ADMIN
			 ,           to_char(SCHOOL_DATE, 'YYYYMMDD') AS SCHOOL_DATE 
			FROM         $table 
			WHERE        SCHOOL_DATE IN ($school_dates) 
			 AND         COURSE_PERIOD_ID = '$user_course_period'"
			. (($table == 'LUNCH_PERIOD') ? " AND    TABLE_NAME='$_REQUEST[table]'" : '')
			), array(), array('STUDENT_ID', 'SCHOOL_DATE'));
	
	foreach ($_REQUEST['past_attendance'] as $student_id=>$dates) {
		foreach ($dates as $date=>$value) {
			if ($current_past_RET[$student_id][$date]) {
				$sql = "
						UPDATE       $table 
						SET          ATTENDANCE_TEACHER_CODE = '$value'";
						
				if (true || $current_RET[$student_id][1]['ADMIN']!='Y') {
					$sql .= "
						 , ATTENDANCE_CODE = '$value'";
				}
				$sql .= "
						WHERE SCHOOL_DATE = '$date' 
						 AND COURSE_PERIOD_ID = '$user_course_period'
						 AND STUDENT_ID = '$student_id'
						";
			}
			else
				$mp_date = GetCurrentMP('QTR', $date);
				$sql = "
						INSERT INTO  $table 
						(  STUDENT_ID
						 , SCHOOL_DATE
						 , MARKING_PERIOD_ID
						 , PERIOD_ID
						 , COURSE_PERIOD_ID
						 , ATTENDANCE_CODE
						 , ATTENDANCE_TEACHER_CODE "
						 . (($table == 'LUNCH_PERIOD') ? ', TABLE_NAME' : '') ."
						) values
						(  '$student_id'
						 , '$date'
						 , '$mp_date'
						 , '$user_period'
						 , '$user_course_period'
						 , '$value'
						 , '$value' "
						 . (($table == 'LUNCH_PERIOD') ? ", '$_REQUEST[table]'" : '') ."
						)
						";

			if ($value != '-') {
				DBQuery($sql);
				if ($_REQUEST['table'] == '0') {
					UpdateAttendanceDaily($student_id, $date);
				}
			}
		}
	}

	unset($_SESSION['_REQUEST_vars']['past_attendance']);
	unset($_REQUEST['past_attendance']);
}

$codes_RET = DBGet(DBQuery("
		SELECT       ID
		 ,           TITLE
		 ,           DEFAULT_CODE
		 ,           SHORT_NAME 
		FROM         ATTENDANCE_CODES 
		WHERE        SCHOOL_ID = '$user_school' 
		 AND         SYEAR = '$user_syear' 
		 AND         TYPE = 'teacher' 
		 AND         TABLE_NAME='$_REQUEST[table]' 
		ORDER BY     SORT_ORDER
		"));

if (count($codes_RET)) {
	foreach ($codes_RET as $code) {
		$extra['SELECT'] .= ", '' AS CODE_" . $code['ID'];
		
		if ($code['DEFAULT_CODE'] == 'Y') {
			$extra['functions']['CODE_'.$code['ID']] = '_makeRadioSelected';
		}
		else {
			$extra['functions']['CODE_'.$code['ID']] = '_makeRadio';
		}
		
		$columns['CODE_'.$code['ID']] = $code['TITLE'];
	}
}
else {
	$columns = array();
}

if (!is_array($extra['functions'])) {
	$extra['functions'] = array();
}

$LO_columns = array(
		  'FULL_NAME'=>_('Student')
		, 'STUDENT_ID'=>_('Student ID')
		, 'GRADE_ID'=>_('Grade')
		) + $columns;
		
if (Preferences('DISPLAY_STUDENT_ID') != 'Y') {
	unset($LO_columns['STUDENT_ID']);
}

if (Preferences('DISPLAY_GRADE') != 'Y') {
	unset($LO_columns['GRADE_ID']);
}

if (SystemPreferences('PAST_ATTENDANCE_DAYS') != 0) {
	for($i = SystemPreferences('PAST_ATTENDANCE_DAYS'); $i >= 1; $i--) {
		$date_no_dash = str_replace('-', '', $dates_RET[$i]['SCHOOL_DATE']);
		$past_columns["PAST_$date_no_dash"]	= ShortDate($dates_RET[$i]['SCHOOL_DATE']);
			
		$extra['functions']["PAST_$date_no_dash"] = '_makePastPulldown';
			
		$extra['SELECT'] .= ", NULL AS PAST_$date_no_dash ";
	}
	
	$past_extra['SELECT_ONLY'] = '
			  ap.ATTENDANCE_CODE
			, ssm.STUDENT_ID
			, to_char(ap.SCHOOL_DATE, \'YYYYMMDD\') AS SCHOOL_DATE';
			
	$past_extra['FROM'] = "
			,            $table ap ";
			
	$past_extra['WHERE'] = " 
			 AND           ap.STUDENT_ID = ssm.STUDENT_ID 
			 AND           ap.COURSE_PERIOD_ID = '$user_course_period' 
			 AND           ap.SCHOOL_DATE IN ($school_dates) ";
			 
	$past_extra['group'] = array('STUDENT_ID', 'SCHOOL_DATE');
	
	$past_att_RET = GetStuList($past_extra);
	
	$LO_columns = $past_columns + $LO_columns;
}

$extra['functions'] += array('FULL_NAME'=>'_makeTipMessage');
$stu_RET = GetStuList($extra);

if ($_REQUEST['table'] == '0') {
	$completed_RET = DBGet(DBQuery("
			SELECT       'Y' as COMPLETED 
			FROM         ATTENDANCE_COMPLETED 
			WHERE        STAFF_ID = '$user_staff_id' 
			 AND         SCHOOL_DATE = '$db_date' 
			 AND         PERIOD_ID='$user_period'
			"));
			
	if ($completed_RET[1]['COMPLETED'] == 'Y') {
		$note = ErrorMessage(array(
				'<img src="assets/check.gif">' 
				. _('You have taken attendance today for this period.')
				), 'note');
	}
}

echo '<form 
		action="Modules.php?modname='.$_REQUEST['modname'].'&table='.$_REQUEST['table'].'"
		method="POST"
		>';
		
DrawHeader($note, '<input type="submit" value="'._('Save').'" />');

$tabs[] = array('title'=>_('Attendance'), 'link'=>"Modules.php?modname=$_REQUEST[modname]&table=0");

$categories_RET = DBGet(DBQuery("
		SELECT       ID
		 ,           TITLE 
		FROM         ATTENDANCE_CODE_CATEGORIES 
		WHERE        SYEAR = '$user_syear'
		 AND         SCHOOL_ID='$user_school'
		"));

foreach ($categories_RET as $category) {
	$tabs[] = array(
			  'title' => $category['TITLE']
			, 'link' => "Modules.php?modname=$_REQUEST[modname]&table=".$category['ID']
			);
}

echo '<BR>';
if (count($categories_RET)) {
	echo '
		<CENTER>
			'.WrapTabs($tabs, "Modules.php?modname=$_REQUEST[modname]&table=$_REQUEST[table]").'
		</CENTER>';
	$extra = array(
			'download' => false
			, 'search' => false
			);
}
else {
	$extra = array();
	$singular = _('Student');
	$plural = _('Students');
}

ListOutput($stu_RET, $LO_columns, $singular, $plural, array(), array(), $extra);
echo '<CENTER><INPUT type=submit value='._('Save').'></CENTER>';
echo "</FORM>";

function _makeRadio($value, $title)
{	global $THIS_RET
	,      $current_RET
	;
	
	if ($current_RET[$THIS_RET['STUDENT_ID']][1]['ATTENDANCE_TEACHER_CODE'] == substr($title, 5)) {
		return "<INPUT type=radio name=attendance[".$THIS_RET['STUDENT_ID']."] value='$title' CHECKED>";
	}
	else {
		return "<INPUT type=radio name=attendance[".$THIS_RET['STUDENT_ID']."] value='$title'>";
	}
}

function _makeRadioSelected($value, $title)
{	global $THIS_RET
	,      $current_RET
	;
	
	if ($current_RET[$THIS_RET['STUDENT_ID']][1]['ATTENDANCE_TEACHER_CODE'] != '' 
	&& ($current_RET[$THIS_RET['STUDENT_ID']][1]['ATTENDANCE_TEACHER_CODE'] != substr($title, 5))
	){
		return "<INPUT type=radio name=attendance[".$THIS_RET['STUDENT_ID']."] value='$title'>";
	}
	else {
		return "<INPUT type=radio name=attendance[".$THIS_RET['STUDENT_ID']."] value='$title' CHECKED>";
	}
}

function _makeTipMessage($value, $title)
{	global $THIS_RET
	,      $StudentPicturesPath
	;

	if ($StudentPicturesPath && ($file = @fopen($StudentPicturesPath.($syear = UserSyear()).'/'.$THIS_RET['STUDENT_ID'].'.JPG','r') || $file = @fopen($StudentPicturesPath.($syear = (UserSyear()-1)).'/'.$THIS_RET['STUDENT_ID'].'.JPG','r')))
		return '<DIV onMouseOver=\'stm(["'.str_replace("'",'&rsquo;',$THIS_RET['FULL_NAME']).'","<IMG SRC='.str_replace('\\','\\\\',$StudentPicturesPath).$syear.'/'.$THIS_RET['STUDENT_ID'].'.JPG>"],["white","#333366","","","",,"black","#e8e8ff","","","",,,,2,"#333366",2,,,,,"",,,,]);\' onMouseOut=\'htm()\'>'.$value.'</DIV>';
	else
		return $value;
}

function _makePastPulldown($value,$title)
{	global $THIS_RET
	,      $codes_RET
	,      $past_att_RET
	;
	
	$school_date = substr($title, 5);
	$val = $past_att_RET[$THIS_RET['STUDENT_ID']][$school_date][1]['ATTENDANCE_CODE'];

	foreach ($codes_RET as $code)
		$options[$code['ID']] = $code['SHORT_NAME'];

	if ($val=='')
		$val = '-';
	return SelectInput($val, 'past_attendance['.$THIS_RET['STUDENT_ID'].']['.$school_date.']', '', $options, false);
}
?>